<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="dataForm.key"
        placeholder="参数名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="getDataList()"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getDataList()"
      >查询</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="addOrUpdateHandle()"
      >新增</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="danger"
        icon="el-icon-delete"
        @click="deleteHandle()"
        :disabled="dataListSelections.length <= 0"
      >批量删除</el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>

      <el-table-column prop="id" header-align="center" align="center" label="主键"></el-table-column>

      <el-table-column prop="name" header-align="center" align="center" label="名称"></el-table-column>

      <el-table-column prop="age" header-align="center" align="center" label="年龄"></el-table-column>

      <el-table-column prop="salary" header-align="center" align="center" label="薪水"></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="addOrUpdateHandle(scope.row.id)">Edit</el-button>
          <el-button size="mini" type="danger" @click="deleteHandle(scope.row.id)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="totalCount>0"
      :total="totalCount"
      :page.sync="pageIndex"
      :limit.sync="pageSize"
      @pagination="getDataList()"
    />

    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./table-add-or-update";

import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "ComplexTable",
  components: { Pagination, AddOrUpdate },
  directives: { waves },
  data() {
    return {
      dataForm: {
        key: "",
      },
      dataList: [],
      totalCount: 0,
      pageIndex: 1,
      addOrUpdateVisible: false,
      tableKey: 0,
      pageSize: 10,
      dataListLoading: false,
      dataListSelections: [],
      downloadLoading: false,
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    getDataList() {
      console.log("this.pageIndex", this.pageIndex);
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/api/generator/generator/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
        }),
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalCount = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalCount = 0;
        }
        this.dataListLoading = false;
      });
    },

    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },

    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/api/generator/generator/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then((data) => {
            if (data && data.code === 0) {
              this.$notify({
                title: "Success",
                message: "Delete Successfully",
                type: "success",
                duration: 500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch((e) => e);
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status",
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list",
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.dataList.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
  },
};
</script>
